package com.project.util;

import com.project.server.Servlet;

import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ServletFactory {
    private static Properties pro = new Properties();
    private static Map<String, Servlet> servletMap= new HashMap<>();
    static {
        try {
            pro.load(new FileReader("D:\\java\\JAVA-Two\\chapter2\\classTest\\class.txt"));
            //得到属性文件的键集合
            Set<String> keySet = pro.stringPropertyNames();
            for (String key:keySet) {
                //根据键，得到值
                String classPath = pro.getProperty(key);
                //加载类，得到类模板
                Class c =Class.forName(classPath);

                servletMap.put(key,(Servlet) c.getConstructor().newInstance());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据URL，得到servlet实现类对象
     * @param url 客户端请求的URL
     * @return servlet
     */
    public static Servlet getServlet(String url){
        return servletMap.get(url);
    }
}
